//
//  JWCalendarModel.m
//  SiqiCalendar
//
//  Created by sunjiawen on 2018/4/4.
//  Copyright © 2018年 sjw. All rights reserved.
//

#import "JWCalendarModel.h"

@implementation JWCalendarModel
+ (instancetype)modelWithCalendarModel:(JWCalendarModel *)calendarModel {
    
    JWCalendarModel *model = [[JWCalendarModel alloc]init];
    
    model.calendarId = calendarModel.calendarId;
    model.calendarName = calendarModel.calendarName;
    model.exchangedDate = calendarModel.exchangedDate;
    
    RLMArray *newScheduleStatus = [[RLMArray alloc]initWithObjectClassName:JWCalendarModel.className];
    for (JWScheduleModel *schedule in calendarModel.scheduleStatus) {
        [newScheduleStatus addObject:schedule];
    }
    model.scheduleStatus = (RLMArray<JWScheduleModel *><JWScheduleModel> *)newScheduleStatus;
    
    model.firstDate = calendarModel.firstDate;
    model.isDefault = calendarModel.isDefault;
    model.orderIndex = calendarModel.orderIndex;
    
    return model;
}

+ (NSString *)primaryKey {
    return kCalendarId;
}

- (void)updateCalendarName:(NSString *)calendarName {
    if ([calendarName isEqualToString: self.calendarName]) return;
    
    RLMRealm *realm = RLMRealm.defaultRealm;
    [realm beginWriteTransaction];
    self.calendarName = calendarName;
    [realm commitWriteTransaction];
}

- (void)updateFirstDate:(NSDate *)firstDate {
    RLMRealm *realm = RLMRealm.defaultRealm;
    [realm beginWriteTransaction];
    self.firstDate = firstDate;
    [realm commitWriteTransaction];
}

- (void)updateIsDefault:(NSNumber<RLMBool> *)isDefault {
    // 设置当前对象为默认后，其他所有的对象都置为 非默认
    RLMRealm *realm = RLMRealm.defaultRealm;
    
    RLMResults *calendars = [JWCalendarModel objectsWhere:@"isDefault = %@",@YES];
    
    [realm transactionWithBlock:^{
        for (JWCalendarModel *model in calendars) {
            model.isDefault = @NO;
        }
        self.isDefault = @YES;
    }];
}

- (void)updateOrderIndex:(NSNumber<RLMInt> *)orderIndex {
    if (orderIndex.intValue == self.orderIndex.intValue) return;
    
    RLMRealm *realm = RLMRealm.defaultRealm;
    [realm beginWriteTransaction];
    self.orderIndex = orderIndex;
    [realm commitWriteTransaction];
}

- (void)updateExchangedDate:(NSString *)exchangedDate {
    if ([exchangedDate isEqualToString: self.exchangedDate]) return;
    
    RLMRealm *realm = RLMRealm.defaultRealm;
    JWCalendarModel *calendar = [JWCalendarModel objectsWhere:@"calendarId = %@",self.calendarId].firstObject;

    [realm transactionWithBlock:^{
        calendar.exchangedDate = exchangedDate;
    }];
}

@end

